import { useEffect, useState, lazy } from 'react'
import { RouterProvider, createHashRouter } from 'react-router-dom'
import Layout from '../layout/Layout'
import NotFound from '../NotFound'
import Login from '../layout/login'
import Kanban from '../pages/kanban'

import { getAdminMenus } from '../mockData'

import { MenuItem, Moudle, Component } from '../types/index.d'

// 菜单入口文件 约定index为默认页面
const modules = import.meta.glob('./pages/*/*/index.tsx')

const components = Object.keys(modules).reduce((pre, cur) => {
  const key = cur.replace('./pages/', '')
  pre[key] = modules[cur] as Moudle
  return pre
}, {} as Component)

const router = createHashRouter([
  {
    path: '/',
    Component: Layout,
    children: []
  },
  {
    path: '/login',
    Component: Login,
    children: []
  },
  {
    path: '/kanban',
    Component: Kanban,
    children: []
  },
  {
    path: '*',
    Component: NotFound
  }
])


useEffect(() => {
  getAdminMenus().then((adminMenus: MenuItem[]) => {
    // setMenus(adminMenus)
    // setLoading(false)

    const pages: any[] = []

    adminMenus.forEach((item) => {
      if (item.filePath) {
        const filePath = `${item.filePath}/index.tsx`
        pages.push({
          id: item.path,
          path: item.path,
          Component: components[filePath]
            ? lazy(components[filePath])
            : () => <div>页面待开发...</div>
        })
      }
    })

    router.routes[0].children = pages
  })
}, [])

function Router() {
  return <RouterProvider router={router} />
}

export default Router
